<template>
  <div class="login-container">
    <div class="login-box">
      <div class="header">
        <img class="logo" src="/logo.png" alt="Logo">
        <h2 class="title">宠喵管理后台</h2>
      </div>
      <div class="form">
        <el-form ref="loginFormRef" label-position="top" label-width="auto" :model="user" :rules="checkUser">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username" class="content" size="large" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="user.password" class="content" size="large" type="password" placeholder="请输入密码"
              show-password />
          </el-form-item>
        </el-form>
        <el-button type="primary" class="button" size="large" :loading="isLogin" @click="login">LOGIN</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// 表单数据
const user = ref({
  username: '',
  password: ''
})
// 表单校验规则
const checkUser = ref({
  username: [
    { required: true, message: '用户名不能为空!', trigger: 'change' }
  ],
  password: [
    { required: true, message: '密码不能为空!', trigger: 'change' }
  ]
})
// 登录校验逻辑
import { loginService } from '@/api/user.js'
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const tokenStore = useTokenStore()
const isLogin = ref(false)
const loginFormRef = ref()
const login = () => {
  isLogin.value = true
  loginFormRef.value.validate().then(async () => {
    const res = await loginService(user.value)
    if (res.code === 0) {
      tokenStore.setToken(res.data)
      router.push('/home')
    }
  }).catch(() => { })
  isLogin.value = false
}
</script>

<style scoped lang="scss">
.login-container {
  position: absolute;
  top: 0;
  left: 0;
  overflow-y: auto;
  height: 100vh;
  width: 100vw;
  background-color: #EEF1F4;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  height: 75vh;
  width: 50vw;
  background-color: #fff;
  text-align: center;
  padding: 10vh;

  .header {
    display: flex;
    justify-content: center;
    align-items: center;

    .logo {
      width: 5vw;
      margin-right: 1rem;
    }

    .title {
      font-size: 1.5vw;
    }
  }
}

.form {
  margin: 5vh 10vw;

  .button {
    width: 100%;
    margin-top: 10%;
  }
}
</style>
